package admin

import (
	"github.com/gin-gonic/gin"
	"net/http"
	"strconv"
	"strings"
	"time"
	. "xm_shop/database"
	. "xm_shop/models"
)

type GoodsTypeController struct{}

// 获取全部的商品类型
func (g GoodsTypeController) Index(context *gin.Context) {
	var goodsTypeList []GoodsType
	DB.Find(&goodsTypeList)
	context.JSON(http.StatusOK, gin.H{
		"success":       true,
		"goodsTypeList": goodsTypeList,
	})
}

// 新增商品类型
func (g GoodsTypeController) Add(context *gin.Context) {
	title := strings.Trim(context.PostForm("title"), " ")
	description := strings.Trim(context.PostForm("description"), " ")
	status, err1 := strconv.Atoi(context.PostForm("status"))
	if err1 != nil {
		context.String(http.StatusBadRequest, "参数有误")
		return
	}
	// 创建结构体实例
	goodsType := GoodsType{
		Title:       title,
		Description: description,
		Status:      status,
		AddTime:     int(time.Now().Unix()),
	}
	if err2 := DB.Create(&goodsType).Error; err2 != nil {
		context.String(http.StatusBadRequest, "新增商品失败")
		return
	}
	context.JSON(http.StatusOK, gin.H{
		"success":   true,
		"goodsType": goodsType,
	})
}

// 编辑商品类型
func (g GoodsTypeController) Edit(context *gin.Context) {
	id, err1 := strconv.Atoi(context.Param("id"))
	title := strings.Trim(context.PostForm("title"), " ")
	description := strings.Trim(context.PostForm("description"), " ")
	status, err2 := strconv.Atoi(context.PostForm("status"))
	if err1 != nil || err2 != nil {
		context.String(http.StatusBadRequest, "参数有误")
		return
	}
	// 检索
	var goodsType GoodsType
	DB.Where("id = ?", id).Take(&goodsType)
	if goodsType.ID == 0 {
		context.String(http.StatusBadRequest, "商品类型不存在")
		return
	}
	goodsType.Title = title
	goodsType.Description = description
	goodsType.Status = status
	if err3 := DB.Save(&goodsType).Error; err3 != nil {
		context.String(http.StatusBadRequest, "修改失败")
		return
	}
	context.JSON(http.StatusOK, gin.H{
		"success":   true,
		"goodsType": goodsType,
	})
}

// 删除商品类型
func (g GoodsTypeController) Delete(context *gin.Context) {
	id, err1 := strconv.Atoi(context.Param("id"))
	if err1 != nil {
		context.String(http.StatusBadRequest, "参数有误")
		return
	}
	// 检索
	var goodsType GoodsType
	DB.Where("id = ?", id).Take(&goodsType)
	if err2 := DB.Delete(&goodsType).Error; err2 != nil {
		context.String(http.StatusBadRequest, "删除失败")
		return
	}
	context.JSON(http.StatusOK, gin.H{
		"success": true,
	})
}
